export class InputSystem {
    private canvas: HTMLCanvasElement;
    private isMouseDown: boolean = false;
    private mousePosition: { x: number; y: number } = { x: 0, y: 0 };
    
    // 事件回调
    public onMouseClick: ((x: number, y: number) => void) | null = null;
    public onMouseMove: ((x: number, y: number) => void) | null = null;
    public onMouseDown: ((x: number, y: number) => void) | null = null;
    public onMouseUp: ((x: number, y: number) => void) | null = null;
    public onKeyDown: ((key: string) => void) | null = null;
    public onKeyUp: ((key: string) => void) | null = null;

    constructor(canvas: HTMLCanvasElement) {
        this.canvas = canvas;
    }

    async init(): Promise<void> {
        console.log('🖱️ 初始化输入系统...');
        this.setupEventListeners();
        console.log('✅ 输入系统初始化完成');
    }

    update(deltaTime: number): void {
        // 输入系统的更新逻辑（如果需要的话）
    }

    private setupEventListeners(): void {
        // 鼠标事件
        this.canvas.addEventListener('click', this.handleMouseClick.bind(this));
        this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
        this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
        this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
        this.canvas.addEventListener('contextmenu', this.handleRightClick.bind(this));

        // 键盘事件
        document.addEventListener('keydown', this.handleKeyDown.bind(this));
        document.addEventListener('keyup', this.handleKeyUp.bind(this));

        // 防止右键菜单
        this.canvas.addEventListener('contextmenu', (e) => e.preventDefault());
    }

    private handleMouseClick(event: MouseEvent): void {
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        this.mousePosition = { x, y };
        
        if (this.onMouseClick) {
            this.onMouseClick(x, y);
        }
    }

    private handleMouseMove(event: MouseEvent): void {
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        this.mousePosition = { x, y };
        
        if (this.onMouseMove) {
            this.onMouseMove(x, y);
        }
    }

    private handleMouseDown(event: MouseEvent): void {
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        this.isMouseDown = true;
        this.mousePosition = { x, y };
        
        if (this.onMouseDown) {
            this.onMouseDown(x, y);
        }
    }

    private handleMouseUp(event: MouseEvent): void {
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        this.isMouseDown = false;
        this.mousePosition = { x, y };
        
        if (this.onMouseUp) {
            this.onMouseUp(x, y);
        }
    }

    private handleRightClick(event: MouseEvent): void {
        event.preventDefault();
        
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        console.log(`🖱️ 右键点击: (${x}, ${y})`);
        // 这里可以处理右键特殊功能，比如设置优先级
    }

    private handleKeyDown(event: KeyboardEvent): void {
        if (this.onKeyDown) {
            this.onKeyDown(event.key);
        }

        // 处理一些默认的快捷键
        switch (event.key) {
            case 'Escape':
                console.log('🚫 取消当前操作');
                break;
            case '1':
                console.log('🔧 快捷键选择铁穹系统');
                break;
            case '2':
                console.log('🚀 快捷键选择箭-3系统');
                break;
            case '3':
                console.log('📡 快捷键选择绿松雷达');
                break;
            case 'Space':
                event.preventDefault();
                console.log('⏸️ 暂停/恢复游戏');
                break;
        }
    }

    private handleKeyUp(event: KeyboardEvent): void {
        if (this.onKeyUp) {
            this.onKeyUp(event.key);
        }
    }

    // 公共接口
    public getMousePosition(): { x: number; y: number } {
        return { ...this.mousePosition };
    }

    public isMousePressed(): boolean {
        return this.isMouseDown;
    }

    // 将屏幕坐标转换为游戏世界坐标
    public screenToWorld(screenX: number, screenY: number): { x: number; y: number } {
        // 目前1:1映射，后续可能需要考虑缩放和偏移
        return { x: screenX, y: screenY };
    }

    // 检查点是否在指定区域内
    public isPointInRect(x: number, y: number, rectX: number, rectY: number, width: number, height: number): boolean {
        return x >= rectX && x <= rectX + width && y >= rectY && y <= rectY + height;
    }

    // 检查点是否在圆形区域内
    public isPointInCircle(x: number, y: number, centerX: number, centerY: number, radius: number): boolean {
        const dx = x - centerX;
        const dy = y - centerY;
        return dx * dx + dy * dy <= radius * radius;
    }

    // 清理事件监听器
    public destroy(): void {
        this.canvas.removeEventListener('click', this.handleMouseClick.bind(this));
        this.canvas.removeEventListener('mousemove', this.handleMouseMove.bind(this));
        this.canvas.removeEventListener('mousedown', this.handleMouseDown.bind(this));
        this.canvas.removeEventListener('mouseup', this.handleMouseUp.bind(this));
        this.canvas.removeEventListener('contextmenu', this.handleRightClick.bind(this));
        
        document.removeEventListener('keydown', this.handleKeyDown.bind(this));
        document.removeEventListener('keyup', this.handleKeyUp.bind(this));
    }
}
